package cn.dong.vod.service.impl;

import cn.dong.vod.handler.AliyunVodSDKUtils;
import cn.dong.vod.handler.VodHandler;
import cn.dong.vod.service.AdminVideoService;
import cn.dong.base.handler.CustomException;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
@Slf4j
public class AdminVideoServiceImpl implements AdminVideoService {


    /**
     * 上传视频
     *
     * @param inputStream
     * @param originalFilename
     * @return
     */
    public String upload(String originalFilename, InputStream inputStream) throws IOException {
        UploadStreamRequest request = new UploadStreamRequest(VodHandler.ACCESS_KEY_ID_INFO, VodHandler.ACCESS_KEY_SECRET_INFO
                , originalFilename.substring(0, originalFilename.indexOf('.'))
                , originalFilename, inputStream);
        /* 模板组ID(可选) */
//        request.setTemplateGroupId(VodHandler.CODING_TEMPLATE);
//        /* 工作流ID(可选) */
//        request.setWorkflowId(VodHandler.WORK_STREAM);


        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);


        String videoId = response.getVideoId();
        if (StringUtils.isEmpty(videoId)) {
            log.error("阿里云上传失败：" + response.getCode() + "-" + response.getMessage());
            throw new CustomException(40000, "视频上传失败！");
        }
        return videoId;
    }

    /**
     * 删除视频
     *
     * @param videoId
     * @return
     */
    public boolean delete(String videoId) throws ClientException {
        try {
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(VodHandler.ACCESS_KEY_ID_INFO, VodHandler.ACCESS_KEY_SECRET_INFO);
            DeleteVideoRequest request = new DeleteVideoRequest();
            //支持传入多个视频ID，多个用逗号分隔
            request.setVideoIds(videoId);
            DeleteVideoResponse response = client.getAcsResponse(request);

        } catch (Exception e) {
            log.warn("--------> 删除视频错误！");
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
            return false;
        }
        return true;
    }

    /**
     * 批量删除
     *
     * @param videoIds
     * @return
     */
    public void deleteByIds(List<String> videoIds) throws ClientException {
        // 查询全部的小结，获取小结的源id，进行删除，阿里云限制一次性只能删除20个,用,分割
        // 遍历
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < videoIds.size(); i++) {
            sb.append(videoIds.get(i));
            // 判断
            if (i % 20 == 19 || (i == videoIds.size() - 1)) {
                // 提交删除
                delete(sb.toString());
                // 打印日志
                log.info("删除章节的视频：" + sb.toString());
                // 清空字符串
                sb = new StringBuffer();
            } else {
                // 增加逗号
                sb.append(",");
            }
        }
    }

    /**
     * 根据视频id获取凭证
     *
     * @param id
     * @return
     */
    public String getPlayAuth(String id) throws ClientException {
        //初始化客户端、请求对象和相应对象
        DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(VodHandler.ACCESS_KEY_ID_INFO, VodHandler.ACCESS_KEY_SECRET_INFO);
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        //设置请求参数
        request.setVideoId(id);
        //获取请求响应
        GetVideoPlayAuthResponse response  = client.getAcsResponse(request);
        return response.getPlayAuth();
    }


}
